package leetcode

//https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/
/**
 * 使用栈，如果是abc连续的，跳过到下一个位置，如果不是abc，那么先入栈，直到遇到c，然后出站前两个看是否是ab，
 * 否则not valid
 */

fun main(args: Array<String>) {

    println(isAbcValid("aabcbc"))
}

fun isAbcValid(S: String): Boolean {

    val stack = arrayListOf<Char>()

    var i = 0
    while (i < S.length) {
        val ch = S[i]
        if (ch == 'a') {
            if (i + 1 < S.length && i + 2 < S.length) {
                if (S[i + 1] == 'b' && S[i + 2] == 'c')
                    i += 3
                else {
                    stack.add(ch)
                    i++

                }
            } else return false
        } else if (ch == 'c') {
            //从栈中取出两个，如果是ab则继续到下一个
            if (stack.isNotEmpty() && stack.size >= 2) {
                val top = stack.removeAt(stack.lastIndex)
                val top1 = stack.removeAt(stack.lastIndex)
                if (top == 'b' && top1 == 'a') {
                    i++
                } else return false

            } else return false
        } else {
            stack.add(ch)
            i++
        }
    }

    return stack.isEmpty()
}
